package action;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import manager.LoadVariousList;
import manager.ObjectFactory;
import vue.AdminCombinationForm;
import vue.AdminUserForm;
import vue.ChooseGameForm;
import vue.FenetreConnexion;
import bean.UserBean;

public class ActionConnecter extends AbstractAction {

	private FenetreConnexion fenetre;
	UserBean userReturn;
	public ActionConnecter(FenetreConnexion fenetre){
		super();
		this.fenetre = fenetre;
	}

	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		boolean error = false;
		if (fenetre.getLogin().getText().equals("")){
			fenetre.setErrorLogin("*");
			error = true;
		}
		else fenetre.setErrorLogin("");

		if (fenetre.getMdp().getText().equals("")){
			fenetre.setErrorMdp("*");
			error = true;
		}
		else fenetre.setErrorMdp("");

		if (error == false){
			ObjectFactory of = new ObjectFactory();
			UserBean userConnect = of.createUser();
			userConnect.setLogin(fenetre.getLogin().getText());
			userConnect.setPassword(fenetre.getMdp().getText());
			ActionConnection ac = new ActionConnection();
			userReturn = ac.doConnection(userConnect);
			
			if (userReturn != null){ //Connection Reussi
				if(userReturn.getActived())
				{
					LoadVariousList.setIdUser(userReturn.getId());
					//JOptionPane.showMessageDialog(fenetre, fenetre.getBundle().getString("messageBienvenue") + " " + userReturn.getLogin() + " !", fenetre.getBundle().getString("titleBienvenue"), JOptionPane.INFORMATION_MESSAGE);
					if (userReturn.getRole().equals("Joueur"))
					{
						fenetre.dispose();
						ChooseGameForm c = new ChooseGameForm();
					}
					else if (userReturn.getRole().equals("Codeur"))
					{
//						AdminCombinationForm adminCombinationForm = new AdminCombinationForm(userReturn);
						fenetre.dispose();
						AdminCombinationForm adminCombinationForm = new AdminCombinationForm();
					}
					else if (userReturn.getRole().equals("Administrateur"))
					{
						fenetre.dispose();
						AdminUserForm winForm = new AdminUserForm();
					}
				}
				else
				{
					JOptionPane.showMessageDialog(fenetre, fenetre.getBundle().getString("messageErrorActivated") , fenetre.getBundle().getString("titleErrorConnection"), JOptionPane.ERROR_MESSAGE);
				}
			}
			else { //  Login ou mot de passe incorrect
					JOptionPane.showMessageDialog(fenetre, fenetre.getBundle().getString("messageErrorConnection") , fenetre.getBundle().getString("titleErrorConnection"), JOptionPane.ERROR_MESSAGE);
					fenetre.getMdp().setText("");
			}
		}
	}

}
